package com.rulin.asp.sso.service;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.rulin.asp.sso.entity.User;
import com.rulin.asp.sso.entity.UserUtils;
import com.rulin.asp.sso.mapper.UserMapper;

public class SingleUserInterceptor implements HandlerInterceptor {

	@Autowired
	private UserMapper userMapper;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		String url = request.getRequestURI();
		// 如果拦截到的是登录的页面的话放行
		if (url.indexOf("login.jsp") >= 0 || url.indexOf("account/showAccount") >= 0 || url.indexOf("account/toLogin") >= 0) {
			return true;
		}
		// 如果用户名存在放行（即登录放行）
		String userAccount = (String) request.getSession().getAttribute("userAccount");
		if (userAccount != null) {
			String sessionid = userMapper.selectByUserAccount(userAccount).getSessionId();
			if (sessionid.equals(request.getSession().getId())) {
				
				//保存用户信息到当前线程中
				String userName = (String) request.getSession().getAttribute("userName");
				String userId = (String) request.getSession().getAttribute("userId");
				User user = new User();
				user.setAccount(userAccount);
				user.setUserName(userName);
				user.setId(userId);
				UserUtils.set(user);
				
				return true;
			} else {
				response.setStatus(HttpServletResponse.SC_GATEWAY_TIMEOUT);
				response.setContentType("text/html; charset=utf-8");
				PrintWriter out = response.getWriter();
				out.println("<html>");
				out.println("<script>");
				out.println("alert('您的账号在别地登录，您被迫下线')");
				out.println("window.open ('" + request.getContextPath() + "/account/showAccount','_top');");
				out.println("</script>");
				out.println("</html>");
				// request.getRequestDispatcher("login.jsp").forward(request,response);
				return false;
			}
		}
		request.getRequestDispatcher("login.jsp").forward(request, response);
		return false;

	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub

	}

}
